<?php 

class Event_CallCenterPricePostSave extends Crud_Event_Handler 
{
	protected $_type = 'postSave';
	protected $_changed = 0;

	/**
	 * Run handler with options array.
	 * 
	 * @param OrdersRow $row
	 * @return void
	 */
	public function run($row)
	{
		if ($row instanceof Crud_Section_Row) {
			$row = $row->getRow();
		}
		
		if ($this->_getParam('action') == 'add') {
			$row->addLog('%s создал заказ');
			
			$user = $this->_getAdminUser();
			$row->setAdminUserId($user->getId());
		}
		
		$this->_wikimart($row);
			
		$this->_delivery($row);
		$type_script = $this->_getParam('type_script', null);
		if ($type_script == 'percent') {
			$this->_editPercent($row);
		}


		$delivery_sum = $this->_getParam('delivery_sum');
		if($delivery_sum != ''){
			$row->setDeliveryCost($delivery_sum);
			$row->save();
		}
		$this->_toFile($row);
	}

	protected function _editPercent($row)
	{
		$order_id = (int)$this->_getParam('id'); 				    //id заказа
			$percent = $this->_getParam('percent', null); 			//процент
			$user = $this->_getAdminUser(); 						//данные администратора
			$total = $this->_getParam('total', null); 				//общая сумма из формы
		
		$i = 0;
		$b = 0;
		$total_price = 0;
		while(true){
			$no_percent_count = $this->_getParam('no_percent_count_'.$i, null);
			$clean_price = $this->_getParam('clean_price_'.$i, null);
			if(!isset($clean_price)){
				break;
			}

			$total_price += $clean_price * $no_percent_count;
			$i++;
		}

			if($percent > 100.00){
				$percent = 100.00;
			}

			if($percent > 0 && $total != null){						    //если указывали процент в форме, то расчитываем его
				if($total == $total_price){
					$percent_itog = $total - $total * ($percent / 100);	//вычисляем общий процент
					$row->setTotalCost($percent_itog);
					$row->setTotalPrice($total);
				}else{
					$percent_itog = $total_price - $total_price * ($percent / 100);	//вычисляем общий процент
					$row->setTotalCost($percent_itog);
				}
				$row->setPercent($percent);
				$row->setTypeDiscount(1);
				$row->setTimeUpdatePrice(date('Y.m.d H:i:s'));
				$row->setEditName($user->getId());
				$row->save();
			}

			$price_order = Order2productPeer::getInstance();
			$select = Order2productPeer::getInstance()->select();
			$select->where('`order_id` = ?', $order_id);
			$order_price = $price_order->fetchAll($select); 		 // получаем все продукты по заказу

			$pp = array();
			foreach($order_price as $ord){
				$price_ord = $ord['price'];
				$pp[] = $price_ord;
			}


			$i = 0;
			while (true) {
				$no_percent = $this->_getParam('no_percent_'.$i, null);
				$clean_price = $this->_getParam('clean_price_'.$i, null);
				$row2 = $this->_getParam('price_id_'.$i, null);
				if(!isset($no_percent)){
					break;
				}

				$price_p = $pp[$i];

				//если запись из базы, не равна записи пришедшей из формы, то обновляем запись в таблице
				if($price_p != $clean_price && $clean_price != 0.00 && $clean_price != null){

					$data = array(
							'price'=> $clean_price
						);
					$price_order->update($data, 'product_id ='.$row2);
				}


				$i++;
			}
	}
	/**
	 * Замена type_id у заказа, если поле викимарт установлено.
	 * 
	 * @param OrdersRow $row
	 * @return void
	 */	
	protected function _wikimart($row)
	{
		if (!$row->getWikimart()) {
			return ;
		}
		
		$peer = OrderTypePeer::getInstance();
		$select = OrderTypePeer::getInstance()->select();
		$select->where("`order_type`.`key` = 'wikimart'");
		$wiki = $peer->fetchRow($select);
		
		$row->setTypeId($wiki->getId());
		$row->save();
	}

	/**
	 * Set delivery columns.
	 * 
	 * @param OrdersRow $row
	 * @return void
	 */
	protected function _delivery($row)
	{
		// Get delivery row
		$delivery = $row->getDeliveryRowByDeliveryId();
		$isNew = 0;
		if (!$delivery) {
			$delivery = DeliveryPeer::getInstance()->createRow();
			$isNew = 1;
		}

		$params = array(
			'email' => 'email',
			'телефон' => 'phone',
			'имя' => 'firstName',
			'фамилия' => 'lastName',
			'город' => 'city',
			'улица' => 'street',
			'дом' => 'home',
			'корпус' => 'corps',
			'подъезд' => 'porch',
			'этаж' => 'level',
			'квартира' => 'flat',
			'метро' => 'metroId',
			'внутри МКАД' => 'inMkad',
		);

		// Check for required field is filled or throw exception
		$required = array(
			'firstName' => 'имя',
			'lastName' => 'фамилия',
			'phone' => 'телефон',
			'city' => 'город',
			'street' => 'улица',
			'home' => 'дом',
		);

		$erFields = array();
		foreach ($required as $key => $value) {
			if (!$this->_getParam($key)) {
				$erFields[] = $value;
			}
		}

		if ($erFields) {
			$erFields = implode(', ', $erFields);
			throw new Crud_Exception('Заполните обязательные поля: ' . $erFields);
		}

		// Check changed columns
		$changed = array();
		foreach ($params as $key => $param) {
			$get = 'get' . ucfirst($param);
			$value = $delivery->$get();

			if ($value != $this->_getParam($param)) {
				$changed[] = $key;
			}
		}

		// Create new delivery is some value is changed AND delivery has 2 or many orders
		if ($changed) {
			$select = OrdersPeer::getInstance()->select();
			$select->where(OrdersPeer::DELIVERY_ID, $delivery->getId());
			$select->limit(2);
			$rowset = OrdersPeer::getInstance()->fetchAll($select);
			if ($rowset->count() > 1) {
				$nDelivery = DeliveryPeer::getInstance()->createRow();
				if ($delivery->getProfileId()) {
					$nDelivery->setProfileId($delivery->getProfileId());
				}

				$isNew = 1;
				$delivery = $nDelivery;
			}
		}

		// Set new values
		foreach ($params as $param) {
			$value = $this->_getParam($param);
			if ($value == '') $value = null;
			$method = 'set' . ucfirst($param);
			$delivery->$method($value);
		}

		// Save row and update orders
		$delivery->save();
		if ($isNew) {
			$row->setDeliveryId($delivery->getId());
		}

		// Save fio in row
		$row->setFio($delivery->getFirstName() . ' ' . $delivery->getLastName());
		$row->save();

		// Add log
		if ($changed) {
			$changed = implode(', ', $changed);
			$row->addLog('%s изменил поля ' . $changed);
		}
	}
	/**
	 * Call service method (create file for domino)
	 * 
	 * @param OrdersRow $row
	 * @return void
	 */
	protected function _toFile($row)
	{
		$status = OrderStatusPeer::getInstance()->fetchByKey('approved');
		$this->_salesCountInc($row);
		if (($row->getOrderStatusId() == $status->getId()) && $this->_getParam('submit')) {
			$params['bonus'] = $this->_bonused($row);
			OrdersService::getInstance()->ordersToFile($row);
			OrdersService::getInstance()->notifyOrderCreated($row, array(), $params);
		}
	}
	
	protected function _bonused($row)
	{
		$status = OrderStatusPeer::getInstance()->fetchByKey('approved');
		$result = null;
		if (($row->getOrderStatusId() == $status->getId()) && $this->_getParam('submit')) {
			$rowset = LotteryService::getInstance()->getOrderBonusByOrder($row);
			$t = time();
			//чтобы акция стартовала когда необходимо
			if (0 == $rowset->count() && $t >= strtotime('2011-06-01') && $t <= strtotime('2011-06-30')
			) {
				$result = LotteryService::getInstance()->createBonusByOrder($row);
				//@todo отослать email о том что у него бонус??
			}
		}
		return $result;
	}
	
	/**
	 * Увеличиваем число продаж всем продуктам.
	 * 
	 * @param OrdersRow $row
	 * @return void
	 */
	protected function _salesCountInc($row)
	{
		$products = $row->getProductRowsetByOrder2product();
		foreach ($products as $product) {
			$product->setSalesCount($product->getSalesCount() + 1);
			$product->save();
		}
	}
	
}